package com.atguigu.paymentdemo.service.impl;

import com.atguigu.paymentdemo.entity.PaymentInfo;

import com.atguigu.paymentdemo.enums.PayType;
import com.atguigu.paymentdemo.mapper.PaymentInfoMapper;

import com.atguigu.paymentdemo.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
    @Resource
    Gson gson;
    @Resource
    PaymentInfoMapper paymentInfoMapper;

    /**
     * 支付成功生成支付信息
     * @param plaintText
     */

    @Override
    public void createPaymentInfo(String plaintText) {


        log.info("生成支付信息");
        Map notifyMeaasge = gson.fromJson(plaintText,HashMap.class);
       //过滤平台重复回调请求
        String transactionId = (String) notifyMeaasge.get("transaction_id");


        Map amount = (Map) notifyMeaasge.get("amount") ;
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo((String) notifyMeaasge.get("out_trade_no"));
        paymentInfo.setTransactionId(transactionId);

        paymentInfo.setPaymentType(PayType.WXPAY.getType());
        paymentInfo.setTradeType((String) notifyMeaasge.get("trade_type"));
        paymentInfo.setTradeState((String) notifyMeaasge.get("trade_state"));
        //json格式的浮点型，需要先转化成Double，在转integer
        paymentInfo.setPayerTotal(((Double)amount.get("payer_total")).intValue());

        paymentInfo.setContent(plaintText);

        paymentInfoMapper.insert(paymentInfo);
    }

    /**
     * 判断支付信息是否已存在
     * @param orderNo
     * @return
     */

    @Override
    public boolean isExistPaymentInfo(String orderNo) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("order_no",orderNo);
        return this.getOne(queryWrapper)!=null;
    }

}
